package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.utils.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;


/**
 * 入住Service业务层处理
 * 
 * @author dsr
 * @date 2025-09-30
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private ContractMapper contractMapper;



    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    /**
     * 新增入住申请
     * @param checkInApplyDto
     */
    @Override
    @Transactional
    public void addApply(CheckInApplyDto checkInApplyDto) {
        //1.校验老人是否入住，若入住，之间结束
        LambdaQueryWrapper<Elder> Elqw = new LambdaQueryWrapper<>();
        //条件1 判断身份证号唯一性
        Elqw.eq(Elder::getIdCardNo,checkInApplyDto.getCheckInElderDto().getIdCardNo());

        //条件2 老人入住状态是否为1 启用
        Elqw.eq(Elder::getStatus,1);
        //唯一确定老人
        Elder elder = elderMapper.selectOne(Elqw);
        //当老人不为空，则说明该老人已经入住，则结束 抛出异常
        if (ObjectUtil.isNotNull( elder)){
            throw new BaseException("该老人已经入住");
        }

        //2.更新床位状态为已入住
        //查找对应的床对象
        Bed bed = bedMapper.selectBedById(checkInApplyDto.getCheckInConfigDto().getBedId());
        //设置床的状态为已入住
        bed.setBedStatus(1);
        //更新bed
        bedMapper.updateBed(bed);

        //3.新增或修改入住信息

        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        Elder elder1 = insertOrupdateCheckIn(checkInElderDto,bed);

        //4.新增签约办理
        saveContract(checkInApplyDto,elder1);

        //5.新增入住信息
        CheckIn checkIn = saveCheckIn(checkInApplyDto,elder1,bed);

        //6.新增入住配置
        saveCheckInConfig(checkInApplyDto.getCheckInConfigDto(),checkIn);
    }

    /**
     * 入住详情
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {

        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();

        //1.依据id查询入住信息 select * from check_in where id = ?
        CheckIn checkIn = checkInMapper.selectCheckInById(id);

        //2.查询老人信息
        //获取老人id
        Long elderId = checkIn.getElderId();
        //创建老人信息对象
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        //获取老人对象
        Elder elder = elderMapper.selectById(elderId);
        //赋值给入住对象
        //判断老人对象信息是否为空
        BeanUtils.copyProperties(elder,checkInElderVo);
        //获取老人的年龄
        //判断生日是否存在
        if (ObjectUtil.isNull(elder.getBirthday())){
            checkInElderVo.setBirthday("");
        }else {
            LocalDate localDate = LocalDate.parse(elder.getBirthday());
            int age = Period.between(localDate, LocalDate.now()).getYears();
            checkInElderVo.setAge(age);
        }

        //3.查询合同信息
        //创建合同对象
        Contract contract = new Contract();
        //依据老人id查询合同信息select * from contract where elder_id = ?
        contract = contractMapper.selectContractByElderId(elderId);
        checkInDetailVo.setContract(contract);

        //4.查询入住配置信息
        //创建入住配置对象
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        //依据入住id获取入住配置信息
        Long checkInId = checkIn.getId();
        //获取入住配置对象
        CheckInConfig checkInConfig = checkInConfigMapper.selectCheckInConfigBycheckinId(checkInId);
        //赋值给入住配置对象
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        //设置配置入住开始时间，入住结束时间，及 床位
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());

        //5.转换家属列表
        //获取家属列表
        String remark = checkIn.getRemark();
        //判断remark是否为空
        if (ObjectUtil.isNotNull(remark)){
            //不为空则将其转换为json格式
            List<ElderFamilyDto> elderFamilyDtoList = JSON.parseArray(remark, ElderFamilyDto.class);
            List<ElderFamilyVo> elderFamilyVoList = new ArrayList<>();
            //循环DTo将数据转换成vo
            for (ElderFamilyDto elderFamilyDto : elderFamilyDtoList) {
                //创建家属对象
                ElderFamilyVo elderFamilyVo = new ElderFamilyVo();
                //将DTO数据赋给vo
                BeanUtils.copyProperties(elderFamilyDto,elderFamilyVo);
                //添加到列表中
                elderFamilyVoList.add(elderFamilyVo);
            }
            checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        }else {
            //为空则返回空列表
            checkInDetailVo.setElderFamilyVoList(new ArrayList<>());
        }

        //6.整合数据返回
        //将老人信息赋给入住详情对象
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        //将入住配置信息赋给入住详情对象
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        //返回 数据
        return checkInDetailVo;

    }


    //新增或修改入住信息
    private Elder insertOrupdateCheckIn(CheckInElderDto checkInElderDto, Bed bed) {
        //创建入住对象
        Elder elder = new Elder();
        //获取老人信息
        BeanUtils.copyProperties(checkInElderDto,elder);
        //设置入住对象信息
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        //查询老人是否存在

        Elder elderDb = elderMapper.selectOne(new LambdaQueryWrapper<Elder>().eq(Elder::getIdCardNo,checkInElderDto.getIdCardNo()));
       if (ObjectUtil.isNotNull(elderDb)){
           //获取id
           elder.setId(elderDb.getId());
           //更新
           elderMapper.updateById( elder);
       }else {
           //新增老人
           elderMapper.insert(elder);
       }
        return elder;
    }


    //新增签约办理
    private void saveContract(CheckInApplyDto checkInApplyDto, Elder elder1) {
        //创建合同对象
        Contract contract = new Contract();
        //获取合同信息
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(),contract);
        //设置合同信息 老人
        contract.setElderId(elder1.getId().intValue());
        contract.setElderName(elder1.getName());
       //设置合同时间
       contract.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
       contract.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
       //设置状态
        if (LocalDateTime.now().isAfter(contract.getStartDate())){
            contract.setStatus(1);
        }
        //设置合同编号
        contract.setContractNumber("HT"+CodeGenerator.generateContractNumber());
        //保存数据
        contractMapper.insertContract( contract);
    }

    //新增入住信息
    private CheckIn saveCheckIn(CheckInApplyDto checkInApplyDto, Elder elder1, Bed bed) {
        //创建入住对象
        CheckIn checkIn = new CheckIn();
        //设置老人信息
        checkIn.setElderName(elder1.getName());
        checkIn.setElderId(elder1.getId());
        checkIn.setIdCardNo(elder1.getIdCardNo());
        //设置入住信息
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(bed.getBedNumber());
        //设置老人家属信息
        List<ElderFamilyDto> elderFamilyDtoList = checkInApplyDto.getElderFamilyDtoList();
        checkIn.setRemark(JSON.toJSONString(elderFamilyDtoList));
        //保存入住信息
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    //新增入住配置
    private void saveCheckInConfig(CheckInConfigDto checkInConfigDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto,checkInConfig);
        //设置id
        checkInConfig.setCheckInId(checkIn.getId());
        //
        checkInConfigMapper.insert(checkInConfig);

    }

}
